import { segment } from "oicq";
import fetch from "node-fetch";
import plugin from "../../lib/plugins/plugin.js";
import gsfgfg from "../genshin/model/gsCfg.js";
import { createRequire, syncBuiltinESMExports } from "module";
import cfg from "../../lib/config/config.js";
import schedule from "node-schedule";

const dir = "./data/shadiaotu";
const jsonPath = "./data/shadiaotu/json";
const picturePath = "./data/shadiaotu/picture";
const require = createRequire(import.meta.url);
const fs = require("fs");
const path = require("path");

//如果没有data/shadiaotu文件夹，就创建一个，并初始化
if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir);
    fs.mkdirSync(jsonPath);
    fs.mkdirSync(picturePath);
    //创建一个json文件jsonPath/data.json
    fs.writeFileSync(jsonPath + "/data.json", "[]");
}

export class example extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: "沙雕图",
            /** 功能描述 */
            dsc: "简单开发示例",
            /** https://oicqjs.github.io/oicq/#events */
            event: "message",
            /** 优先级，数字越小等级越高 */
            priority: 5000,
            rule: [
                {
                    /** 命令正则匹配 */
                    reg: "^#?添加沙雕图$",
                    /** 执行方法 */
                    fnc: "tips",
                },
                {
                    /** 命令正则匹配 */
                    reg: "^#?沙雕图$",
                    /** 执行方法 */
                    fnc: "sendSandSculpture",
                },
                {
                    /** 命令正则匹配 */
                    reg: "^#?删除沙雕图",
                    /** 执行方法 */
                    fnc: "delSand",
                },
                {
                    /** 命令正则匹配 */
                    reg: "^#?沙雕图 \\w+",
                    /** 执行方法 */
                    fnc: "sendSandInNumber",
                },
            ],
        });
    }

    async tips(e) {
        if (e.source) {
            let msgRes = (await e.group.getChatHistory(e.source.seq, 1)).pop();
            console.log(`此消息为引用消息`);
            let url = msgRes.message[0].url;
            let md5 = msgRes.message[0].file;
            let senderQQNickName = e.sender.nickname;
            let isReply = true;
            this.addSandSculpture(url, md5, senderQQNickName, isReply);
            return;
        } else {
            e.reply("请发送图片");
            this.setContext("addSandSculpture");
        }
    }

    async addSandSculpture(url, md5, senderQQNickName, isReply = false) {
        if (isReply == true) {
            //如果是引用消息就啥都不做，直接往下
        } else if (this.e.message[0].url && this.e.message[0].file) {
            url = this.e.message[0].url; //获取图片的url
            md5 = this.e.message[0].file; //获取图片的md5
            senderQQNickName = this.e.sender.nickname; //获取发送者的昵称
            this.finish("addSandSculpture"); //结束监听
        } else {
            this.e.reply("哼，不发图就算了 o(￣ヘ￣o＃)");
            this.finish("addSandSculpture"); //结束监听
            return false;
        }

        //获取json文件的元素的个数
        let data = fs.readFileSync(jsonPath + "/data.json");
        let dataJson = JSON.parse(data);
        let totalNumber = dataJson.length;

        //将id url md5 senderQQNickName存入json文件
        let sandPicture = {
            id: totalNumber + 1,
            url: url,
            md5: md5,
            senderQQNickName: senderQQNickName,
        };
        dataJson.push(sandPicture);
        fs.writeFileSync(jsonPath + "/data.json", JSON.stringify(dataJson));
        this.e.reply("添加成功，当前图片沙雕号为：" + (totalNumber + 1));

        //将图片下载到data/shadiaotu/picture文件夹下
        let picture = await fetch(url);
        let pictureStream = fs.createWriteStream(picturePath + "/" + md5);
        picture.body.pipe(pictureStream);
        return;
    }
    async sendSandSculpture(e) {
        //检查是否在CD，如果是主人则无视
        if (e.user_id != cfg.masterQQ) {
            console.log(e.user_id);
            let CD = await redis.get(`Yunzai:SandPicture:CD`);
            if (CD) {
                let timeRemaining = await redis.ttl(`Yunzai:SandPicture:CD`);
                e.reply(`沙雕图还有 ${timeRemaining} 秒 CD`);
                return false;
            }
            //设置CD
            redis.set(`Yunzai:SandPicture:CD`, "1", { EX: 30 });
        }
        //读取json，获取元素总数
        let data = fs.readFileSync(jsonPath + "/data.json");
        let dataJson = JSON.parse(data);
        let totalNumber = dataJson.length;

        //生成一个随机数，范围从1-totalNumber
        let random = Math.floor(Math.random() * totalNumber + 1);

        //得到元素为random的沙雕图的id,md5和发送者的昵称
        let sandPicture = dataJson[random - 1];
        let id = sandPicture.id;
        let md5 = sandPicture.md5;
        let senderQQNickName = sandPicture.senderQQNickName;

        //发送组合消息
        e.reply([
            `沙雕图 —— (${id})`,
            segment.image(`${picturePath}/${md5}`),
            `—— ${senderQQNickName}`,
        ]);

        return;
    }
    async sendSandInNumber(e) {
        //检查是否在CD，如果是主人则无视
        if (e.user_id != cfg.masterQQ) {
            console.log(e.user_id);
            let CD = await redis.get(`Yunzai:SandPicture:CD`);
            if (CD) {
                let timeRemaining = await redis.ttl(`Yunzai:SandPicture:CD`);
                e.reply(`沙雕图还有 ${timeRemaining} 秒 CD`);
                return false;
            }
            //设置CD
            redis.set(`Yunzai:SandPicture:CD`, "1", { EX: 30 });
        }
        let messageId = e.message[0].text.split(" ")[1];
        if (!messageId) {
            e.reply("命令格式：沙雕图+空格+沙雕图号\n例如：沙雕图 1");
            return false;
        }
        //读取json，获取元素总数
        let data = fs.readFileSync(jsonPath + "/data.json");
        let dataJson = JSON.parse(data);
        let totalNumber = dataJson.length;

        for (let i = 0; i < totalNumber; i++) {
            let sandPicture = dataJson[i];
            let searchId = sandPicture.id;
            if (searchId == messageId) {
                let md5 = sandPicture.md5;
                let senderQQNickName = sandPicture.senderQQNickName;
                //发送组合消息
                e.reply([
                    `沙雕图 —— (${sandPicture.id})`,
                    segment.image(`${picturePath}/${md5}`),
                    `—— ${senderQQNickName}`,
                ]);
                return;
            }
        }

        return;
    }
    async delSand(e) {
        //如果发送人不是主人，就不执行
        if (e.user_id != cfg.masterQQ) {
            e.reply("你不是主人，不能删除沙雕图");
            return false;
        }
        let messageId = e.message[0].text.split(" ")[1];
        if (!messageId) {
            e.reply("命令格式：删除沙雕图+空格+沙雕图号\n例如：删除沙雕图 1");
            return false;
        }
        //读取json文件
        let data = fs.readFileSync(jsonPath + "/data.json");
        let dataJson = JSON.parse(data);
        let totalNumber = dataJson.length;
        //遍历json文件，找到对应的沙雕图
        for (let i = 0; i < totalNumber; i++) {
            let sandPicture = dataJson[i];
            let id = sandPicture.id;
            if (id == messageId) {
                //删除json文件中的元素
                dataJson.splice(i, 1);
                fs.writeFileSync(
                    jsonPath + "/data.json",
                    JSON.stringify(dataJson)
                );
                //回复消息，删除成功
                e.reply("删除成功");
                return true;
            }
        }
        //回复消息，删除失败
        e.reply("删除失败，沙雕图不存在");
        return false;
    }
}
